package com.gitee.feizns.webtemplate.commons.upload;

import com.gitee.feizns.webtemplate.commons.upload.processor.DirHandler;
import com.gitee.feizns.webtemplate.commons.upload.processor.ImageBeforeProcessor;
import com.gitee.feizns.webtemplate.commons.upload.processor.Processor;
import com.gitee.feizns.webtemplate.commons.upload.processor.impl.LocalDirProcessor;
import com.gitee.feizns.webtemplate.commons.upload.processor.impl.WebDirProcessor;
import com.gitee.feizns.webtemplate.commons.upload.service.UploadService;
import com.gitee.feizns.webtemplate.commons.upload.service.UploadServiceImpl;
import com.gitee.feizns.webtemplate.commons.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.Collection;
import java.util.Map;

/**
 * @author feizns
 * @since 2019/5/14
 */
@Configuration
@EnableConfigurationProperties(UploadProperties.class)
public class UploadAutoConfiguration {

    @Autowired
    private UploadProperties uploadProperties;

    @Autowired
    private UploadService uploadService;

    @Bean
    public UploadService uploadService() {
        UploadServiceImpl service = new UploadServiceImpl(uploadProperties);
        service.registeredProcessor(new ImageBeforeProcessor(new LocalDirProcessor()));
        service.registeredProcessor(new ImageBeforeProcessor(new WebDirProcessor()));

        Map<MediaType, Class<? extends Processor>> mediaTypeProcess = uploadProperties.getMediaTypeProcess();
        if ( mediaTypeProcess != null ) {
            mediaTypeProcess.forEach((mediaType, val) -> {
                service.registeredProcessor(new DirHandler(mediaType, BeanUtils.newInstance(val)));
            });
        }
        return service;
    }

    @EventListener
    public void upload(UploadEvent event) {
        if ( event.isAsync() )
            uploadService.async(event);
        else
            uploadService.sync(event);
    }

    @Autowired
    private ApplicationContext applicationContext;

    private <T> Collection<T> getBeansOfType(Class<T> type) {
        return this.applicationContext.getBeansOfType(type).values();
    }

}
